package tur.br.moradadosol.view.action;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import tur.br.moradadosol.control.HospedeControl;
import tur.br.moradadosol.control.UserAutentication;
import tur.br.moradadosol.view.form.HospedeForm;

public class HospedeAction extends Action {

	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response)
		throws Exception {
		
		HttpSession session = request.getSession();

		if(!UserAutentication.isUserAutenticated(session)) {
			return mapping.findForward("login");
		}
		
		ActionMessages errors = new ActionMessages();
		
		HospedeForm Form = (HospedeForm) form;
		
		HospedeControl hospedeControl = 
			(HospedeControl) session.getAttribute("hospedeControl");
		if(hospedeControl == null) {
			hospedeControl = new HospedeControl();
		}
		
		int codigoHospede = 0;
		if(request.getParameter("codigoHospede") != null 
			&& !request.getParameter("codigoHospede").equals("")) {
			
			codigoHospede = Integer.parseInt(
				request.getParameter("codigoHospede"));
		}
		
		try {
			
			if(Form.getGravar().length() > 0) {
				String msg = hospedeControl.gravar(Form.getHospede());
				
				errors.add("error", new ActionMessage(msg));
			}
			else if(Form.getCancelar().length() > 0) {
				Form.resetForm();
				Form.reset(mapping, request);
			}
			else if(Form.getDeletar().length() > 0) {
				hospedeControl.deletar(Form.getHospede().getCodigo());
				Form.resetForm();
				Form.reset(mapping, request);
			}
			else if(Form.getProcurar().length() > 0) {
				Form.resetForm();
				Form.reset(mapping, request);
				Form.setHospedes(new ArrayList());
				Form.setNomepesquisa("");
				
				session.setAttribute("pagina", "hospede");
				
				return mapping.findForward("procurahospede");
			}
			else if(Form.getVoltar().length() > 0 && 
					"reserva".equals(session.getAttribute("pagina"))) {
				if(Form.getHospede().getCodigo() > 0) 
					request.setAttribute("codigoHospede", 
						String.valueOf(Form.getHospede().getCodigo()));
				
				return mapping.findForward("reserva");
			}
			else if(codigoHospede != 0) {
				Form.setHospede(hospedeControl.getHospedeByCodigo(
					codigoHospede));
			}
			
		}
		catch (Exception e) {
			e.printStackTrace();
			errors.add("name", new ActionMessage("error.exception"));
		}
		
		if (!errors.isEmpty()) {
			saveErrors(request, errors);
		}
		
		return mapping.getInputForward();

	}
}
